package co.fitstart.api.web.controller.token;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.wechat.support.AppType;
import com.demo2do.core.wechat.support.WechatJsConfig;
import com.demo2do.core.wechat.web.handler.JsApiHandler;

/**
 *
 * @author lute
 *
 */
@Controller
@RequestMapping("/v1/jsconfig")
public class JsconfigApiController {

    private static final Logger logger = LoggerFactory.getLogger(JsconfigApiController.class);

    @Autowired
    private JsApiHandler jsApiHandler;

    /**
     * Generate WeChat JS API configuration object only for WeChat official account.
     *
     * @param curl  the URL string of web page which request WeChat JS configuration
     * @return      the {@link Result} JSON string contains WeChat JS API configuration
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params="curl")
    public @ResponseBody String generateJsConfig(@RequestParam(value = "curl") String curl) {
        Result result = new Result();
        try {
            WechatJsConfig config = jsApiHandler.generateJsConfig(AppType.OFFICIAL, curl);
            if (config != null) {
                result.success().data("jsconfig", config);
            } else {
                result.fail().message("Can not get JS config.");
            }
        } catch (Exception e) {
            logger.error("JsconfigApiController#generateJsConfig - Generating JS config encounters exception: {}", e);
            result.fail().message("request jsconfig error");
        }
        return JsonUtils.toJsonString(result);
    }

}
